package com.zbkj.service.service.order.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.google.common.collect.Maps;
import com.zbkj.dal.base.constants.OrderConstants;
import com.zbkj.dal.base.enums.ExpressOrderType;
import com.zbkj.dal.base.enums.OrderType;
import com.zbkj.dal.base.page.CommonPage;
import com.zbkj.dal.common.exception.CrmebException;
import com.zbkj.dal.common.utils.SecurityUtil;
import com.zbkj.dal.dao.OrderDao;
import com.zbkj.dal.entity.admin.SystemAdmin;
import com.zbkj.dal.entity.order.MerchantOrder;
import com.zbkj.dal.entity.order.Order;
import com.zbkj.dal.entity.order.OrderDetail;
import com.zbkj.dal.entity.order.OrderRentSharedRecord;
import com.zbkj.dal.entity.user.User;
import com.zbkj.dal.pojo.request.order.platform.PlatformPurchaseOrderQueryRequest;
import com.zbkj.dal.pojo.response.OrderInfoFrontDataResponse;
import com.zbkj.dal.pojo.response.OrderInvoiceResponse;
import com.zbkj.dal.pojo.response.order.merchant.MerchantOrderPurchaseDetailNewResponse;
import com.zbkj.dal.pojo.response.order.platform.PlatformOrderPurchasePageNewResponse;
import com.zbkj.service.model.dto.order.OrderInvoiceDTO;
import com.zbkj.service.service.*;
import com.zbkj.service.service.order.platform.AdminPlatformPurchaseOrderV2Service;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author wangzhengyan
 * @date 2024/4/12 9:38 PM
 */
@Service
@Slf4j
public class AdminPlatformPurchaseOrderV2ServiceImpl extends ServiceImpl<OrderDao, Order> implements AdminPlatformPurchaseOrderV2Service {
    @Resource
    private UserService userService;
    @Resource
    private MerchantOrderService merchantOrderService;
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private OrderDao dao;
    @Resource
    private OrderService orderService;
    @Resource
    private OrderInvoiceService orderInvoiceService;

    @Override
    public PageInfo<PlatformOrderPurchasePageNewResponse> getAdminPlatformOrderPurchaseList(PlatformPurchaseOrderQueryRequest request) {
        SystemAdmin systemAdmin = SecurityUtil.getLoginUserVo().getUser();

        Page<Order> startPage = PageHelper.startPage(request.getPage(), request.getLimit());

        MPJLambdaWrapper<Order> lqw = new MPJLambdaWrapper<>();
        lqw.selectAll(Order.class);
        lqw.leftJoin(MerchantOrder.class, MerchantOrder::getPlatOrderNo, Order::getPlatOrderNo);
        lqw.leftJoin(OrderRentSharedRecord.class, OrderRentSharedRecord::getOrderNo, Order::getOrderNo);
//        lqw.select(Order::getOrderNo, Order::getUid, Order::getPayPrice, Order::getPayType, Order::getPaid, Order::getStatus, Order::getRefundStatus,
//                Order::getIsUserDel, Order::getCancelStatus, Order::getType, Order::getCreateTime, Order::getLevel, Order::getReceivingTime);
        lqw.eq(Order::getMerId, systemAdmin.getMerId());
        if (StrUtil.isNotBlank(request.getOrderNo())) {
            lqw.like(MerchantOrder::getOrderNo, URLUtil.decode(request.getOrderNo()));
        }
        // 单据类型不能为空
        request.setType(OrderType.PURCHASE.code());
        if (ObjectUtil.isNotNull(request.getType())) {
            lqw.eq(Order::getType, request.getType());
        }
        if (Objects.nonNull(request.getOrderTimeStart()) && Objects.nonNull(request.getOrderTimeEnd())) {
            lqw.between(Order::getCreateTime, request.getOrderTimeStart(), request.getOrderTimeEnd());
        }
        // 订单状态
        if (CollectionUtils.isNotEmpty(request.getStatusList())) {
            lqw.in(Order::getStatus, request.getStatusList());
        }
        // 验货结果
//        if (Objects.nonNull(request.getVerifyResultCode())) {
//            lqw.eq(OrderRentSharedRecord::getVerifyResult, request.getVerifyResultCode());
//        }
        lqw.eq(Order::getIsMerchantDel, false);
        lqw.eq(Order::getLevel, OrderConstants.ORDER_LEVEL_PLATFORM);
        lqw.orderByDesc(Order::getId);
        List<Order> orderList = dao.selectJoinList(Order.class, lqw);
        if (CollUtil.isEmpty(orderList)) {
            return CommonPage.copyPageInfo(startPage, CollUtil.newArrayList());
        }
        List<Integer> uidList = orderList.stream().map(Order::getUid).distinct().collect(Collectors.toList());
        Map<Integer, User> userMap = userService.getUidMapList(uidList);

//        List<OrderStatus> orderStatuses = Lists.newArrayList();
//        List<String> orderNos = orderList.stream().filter(p -> p.getType() == OrderConstants.ORDER_TYPE_RENT.intValue()).map(Order::getOrderNo).distinct().collect(Collectors.toList());
//        if (CollectionUtils.isNotEmpty(orderNos)) {
//            orderStatuses = orderStatusService.listDeliveryByOrder(orderNos);
//        }
//        List<OrderStatus> finalOrderStatuses = orderStatuses;

        Map<String, List<OrderDetail>> mapByOrderNoList = Maps.newHashMap();
        List<String> orderNos = orderList.stream().filter(p -> p.getType() == OrderConstants.ORDER_TYPE_NORMAL.intValue() && p.getReceivingTime() != null)
                .map(Order::getOrderNo).distinct().collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(orderNos)) {
            mapByOrderNoList = orderDetailService.getMapByOrderNoList(orderNos);
        }

        Map<String, List<OrderDetail>> finalMapByOrderNoList = mapByOrderNoList;
        List<PlatformOrderPurchasePageNewResponse> pageResponses = orderList.stream().map(e -> {
            PlatformOrderPurchasePageNewResponse pageResponse = new PlatformOrderPurchasePageNewResponse();
            BeanUtils.copyProperties(e, pageResponse);
            MerchantOrder merchantOrder = merchantOrderService.getOneByPlatOrderNo(e.getPlatOrderNo());
            pageResponse.setShippingType(merchantOrder.getShippingType());
            pageResponse.setRemark(merchantOrder.getUserRemark());
//            pageResponse.setMerRemark(merchantOrder.getMerchantRemark());
            pageResponse.setNickName(userMap.get(e.getUid()).getNickname());

            // 计算订单到期时间
            return pageResponse;
        }).collect(Collectors.toList());
        return CommonPage.copyPageInfo(startPage, pageResponses);
    }

    @Override
    public MerchantOrderPurchaseDetailNewResponse getAdminPlatformOrderPurchaseDetail(String orderNo) {
        SystemAdmin systemAdmin = SecurityUtil.getLoginUserVo().getUser();
        Order order = orderService.getByOrderNo(orderNo);
        if (order.getIsMerchantDel() || !order.getMerId().equals(systemAdmin.getMerId())) {
            throw new CrmebException("未找到对应订单信息");
        }
        // 订单信息
        MerchantOrderPurchaseDetailNewResponse orderAdminDetailResponse = new MerchantOrderPurchaseDetailNewResponse();
        Order merchantOrder = orderService.getOneByOrderNoAndType(orderNo, OrderType.PURCHASE.getCode());
        BeanUtils.copyProperties(merchantOrder, orderAdminDetailResponse);
        BeanUtils.copyProperties(order, orderAdminDetailResponse);
        List<OrderDetail> orderDetailList = orderDetailService.getByOrderNo(orderNo);
        List<OrderInfoFrontDataResponse> orderInfoList = orderDetailList.stream().map(e -> {
            OrderInfoFrontDataResponse dataResponse = new OrderInfoFrontDataResponse();
            BeanUtils.copyProperties(e, dataResponse);
            return dataResponse;
        }).collect(Collectors.toList());
        orderAdminDetailResponse.setOrderDetailList(orderInfoList);

        // 用户信息
        User user = userService.getById(order.getUid());
        orderAdminDetailResponse.setRealName(user.getNickname());
        orderAdminDetailResponse.setUserPhone(user.getPhone());
        orderAdminDetailResponse.setUserAddress(user.getAddress());
        // 送货信息
        OrderInvoiceDTO expressInfo = orderInvoiceService.findOrderInvoiceByOrderNoAndInvoiceType(orderNo, ExpressOrderType.PURCHASE);
        if (Objects.nonNull(expressInfo)) {
            orderAdminDetailResponse.setShippingType(OrderConstants.ORDER_SHIPPING_TYPE_EXPRESS);
            orderAdminDetailResponse.setDeliveryName(expressInfo.getExpressName());
            orderAdminDetailResponse.setTrackingNumber(expressInfo.getTrackingNumber());
        }
        // 支付信息
        // 商品信息
        return orderAdminDetailResponse;
    }
}
